#pragma once

#include "CrossDefine.h"

#if defined(LD_WIN32) 
#include <windows.h>
#elif defined(LD_LINUX)
#define  CRITICAL_SECTION   pthread_mutex_t
#endif

#include "common.h"

class CCritSect
{
public:
	CCritSect(void)
	{
#ifdef LD_WIN32
		InitializeCriticalSection(&m_cs);
#else
		pthread_mutex_init(&m_cs, NULL);
#endif
	}
	~CCritSect(void)
	{
#ifdef LD_WIN32
		DeleteCriticalSection(&m_cs);
#else
		pthread_mutex_destroy(&m_cs);
#endif
	}
protected:
	CRITICAL_SECTION	m_cs; 
	friend class	CSLock;
};

class	CSLock
{
public:
	CSLock(CCritSect * x_ctrl, bool n_lock = true) 
	{
		m_p_crit_sect = x_ctrl; 
		CHECK(m_p_crit_sect);
#ifdef LD_WIN32
		EnterCriticalSection(&(m_p_crit_sect->m_cs));
#else
		pthread_mutex_lock(&(m_p_crit_sect->m_cs));
#endif
	}

	~CSLock	 (void)
	{
		if(m_p_crit_sect)
		{
			#ifdef LD_WIN32
			LeaveCriticalSection(&(m_p_crit_sect->m_cs));
			#else
			pthread_mutex_unlock(&(m_p_crit_sect->m_cs));
			#endif	
		}
	};
	void un_lock(void)
	{
		if(m_p_crit_sect)
		{
			#ifdef LD_WIN32
			LeaveCriticalSection(&(m_p_crit_sect->m_cs));
			#else
			pthread_mutex_unlock(&(m_p_crit_sect->m_cs));
			#endif				
			m_p_crit_sect=NULL; 
		}
	};
protected:
	CCritSect * m_p_crit_sect;
};
